package com.kool.core.action;

import com.alibaba.fastjson.JSONObject;
import com.kool.core.CoreConstants;
import com.kool.core.base.IBaseAction;
import com.kool.core.cache.KCache;
import com.kool.core.exception.AppException;
import com.kool.core.notify.NotifyServer;
import com.kool.system.bean.SyUserInfoBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.websocket.Session;
import java.util.List;
import java.util.Set;

/**
 * @description:
 * @author: tianhe
 * @create: 2018/12/04 20:51
 */
@Slf4j
@Controller
public class SendMessageAction implements IBaseAction {
    @Override
    @ResponseBody
    @RequestMapping(value = "/notify/send", method = RequestMethod.POST)
    public JSONObject doAction(@RequestBody String sInput) throws AppException {
        JSONObject pkgIn = JSONObject.parseObject(sInput);
        String from = pkgIn.getString("from");
        String to = pkgIn.getString("to");
        String message = pkgIn.getString("message");

        try {
//            Set<String> keySet = NotifyServer.sessionMap.keySet();
//            for (String key : keySet) {
//                Session session = NotifyServer.sessionMap.get(key);
//                session.getBasicRemote().sendText("["+user+"] :" + message);
//            }

            Session friend = NotifyServer.sessionMap.get(to);
            if (friend != null) {
                SyUserInfoBean userInfo = (SyUserInfoBean) KCache.get(CoreConstants.KCACHE_USER, from);
                friend.getBasicRemote().sendText("["+userInfo.getSuiLoginName()+"] :" + message);
            }else{
                //save massage
                SyUserInfoBean userInfo = (SyUserInfoBean) KCache.get(CoreConstants.KCACHE_USER, to);
                System.out.println("用户["+userInfo.getSuiLoginName()+"]未上线");
                Session me = NotifyServer.sessionMap.get(from);
                if (me != null) {
                    me.getBasicRemote().sendText("用户["+userInfo.getSuiLoginName()+"]未上线");
                }
            }

        } catch (Exception e) {
            log.error("通信异常：",e);
        }

        return null;
    }

}
